<?php

namespace app\salesman\model;

use think\facade\Db;
use \app\model\Salesman as AppSalesman;

class Salesman extends AppSalesman
{
    protected $error = '';

    /**
     * 登录.
     */
    public function login($data)
    {
        $salesman = $this->passLogin($data);
        if (false === $salesman) {
            return false;
        }
        $this->loginRecord($salesman);

        return $salesman['id'];
    }

    /**
     * 登录日志.
     */
    public function loginRecord($salesman)
    {
        $data = [
            'salesman_id' => $salesman['id'],
            'username' => $salesman['username'],
            'ip' => request()->ip(),
            'login_at' => date('Y-m-d H:i:s'),
            'useragent' => request()->header('user-agent'),
        ];
        $salesmanLoginModel = new \app\model\SalesmanLoginLog();
        $salesmanLoginModel->save($data);

    }

    /**
     * 账号密码登录.
     */
    public function passLogin($data)
    {
        if (empty($data['username'])) {
            $this->setError('请输入账号');

            return false;
        }
        if (empty($data['password'])) {
            $this->setError('请输入密码');

            return false;
        }

        $lockKey = $data['username'].'_salesman_login_lock_key';
        $val = cache($lockKey);
        if ($val > 3) {
            $this->setError('连续多次密码输入错误，账号已被锁定');

            return false;
        }

        $salesman = self::where('username', $data['username'])
            ->find();
        if (empty($salesman) || !password_verify($data['password'], $salesman['password'])) {
            $this->setError('账号或者密码有误');

            $val = intval($val) + 1;
            cache($lockKey, $val, 3600*24);

            return false;
        }
        if ($salesman['is_deleted']) {
            $this->setError('登录失败，您的账号已被删除，请联系客服人员');

            return false;
        }
        if (1 != $salesman['status']) {
            $this->setError('登录失败，您的账号已经被禁用, 请联系管理员');

            return false;
        }

        cache($lockKey, null);

        return $salesman;
    }



    /**
     * 设置错误信息.
     */
    public function setError($error)
    {
        $this->error = $error;
    }

    /**
     * 获取错误信息.
     */
    public function getError()
    {
        return $this->error;
    }

    /**
     * 修改密码
     */
    public function updatePassword($params)
    {
        Db::startTrans();
        try {
            $model = self::find($params['salesman_id']);
            $model->password = password_hash($params['password'], PASSWORD_DEFAULT);
            $model->save();
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();

            return fail('修改失败：'.$e->getMessage());
        }

        return success('修改成功');
    }




}
